<template>
  <div class="login-container">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label>用户名</label>
        <input v-model="username" required autocomplete="username" />
      </div>
      <div class="form-group">
        <label>密码</label>
        <input v-model="password" type="password" required autocomplete="current-password" />
      </div>
      <div class="form-actions">
        <button type="submit" class="login-btn">登录</button>
        <router-link to="/register" class="link">没有账号？注册</router-link>
      </div>
      <div v-if="error" class="error">{{ error }}</div>
    </form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      username: '',
      password: '',
      error: ''
    }
  },
  methods: {
    ...mapActions('user', ['login']),
    async handleLogin() {
      try {
        const success = await this.login({ 
          username: this.username, 
          password: this.password 
        })
        if (success) {
          const redirect = this.$route.query.redirect || '/'
          this.$router.push(redirect)
        } else {
          this.error = '用户名或密码错误'
        }
      } catch (err) {
        this.error = '登录失败，请稍后重试'
        console.error('Login error:', err)
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 60px auto;
  padding: 2rem;
  background: var(--hover-color);
  border-radius: 10px;
  color: var(--text-color);
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

h2 {
  color: var(--primary-color);
  margin-bottom: 1.5rem;
  text-align: center;
}

.form-group {
  margin-bottom: 1.2rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
}

input {
  width: 100%;
  padding: 0.6rem 1rem;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  font-size: 1rem;
  background: var(--background-color);
  color: var(--text-color);
}

.form-actions {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 1.2rem;
}

.login-btn {
  background: var(--primary-color);
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 0.6rem 2rem;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
}

.login-btn:hover {
  background: #1565c0;
}

.link {
  color: var(--primary-color);
  text-decoration: underline;
  font-size: 0.95rem;
}

.error {
  color: var(--error-color);
  margin-top: 1rem;
  text-align: center;
}
</style> 